package leetcode.hot100;

import leetcode.tester.Tester;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 15.三数之和
 * https://leetcode.cn/problems/3sum/description/?envType=study-plan-v2&envId=top-100-liked
 *
 * @author Liu Yicong
 * @date 2025/10/13
 */
public class Hot6DbpThreeSum {
	public static void main(String[] args) {
		Object[][] inputs = {
				new Object[]{new int[]{-1, 0, 1, 2, -1, -4}},
				new Object[]{new int[]{0, 1, 1},},
				new Object[]{new int[]{0, 0, 0},},
				new Object[]{new int[]{1, 1, -2},},
				new Object[]{new int[]{-100, -70, -60, 110, 120, 130, 160},},
		};
		Object[] outputs = {
				new Object[]{new int[]{-1, -1, 2}, new int[]{-1, 0, 1},},
				new Object[]{},
				new Object[]{new int[]{0, 0, 0}},
				new Object[]{new int[]{-2, 1, 1}},
				new Object[]{new int[]{-100, -60, 160}, new int[]{-70, -60, 130},},
		};
		Tester.test(Tester.wrap(new Hot6DbpThreeSum()::threeSumOpt), inputs, outputs);
	}

	public List<List<Integer>> threeSumOpt(int[] nums) {
		List<List<Integer>> result = new ArrayList<>();
		Arrays.sort(nums);
		for (int i = 0; i < nums.length - 1; i++) {
			int left = i + 1, right = nums.length - 1;
			if (i > 0 && nums[i] == nums[i - 1]) {
				continue;
			}
			while (left < right) {
				int ans = nums[i] + nums[left] + nums[right];
				if (ans == 0) {

					List<Integer> list = new ArrayList<>(Arrays.asList(nums[i],nums[left],nums[right]));
					result.add(list);
					while (left < right && nums[left] == nums[left + 1]) {
						left++;
					}
					// 跳过重复的right元素
					while (left < right && nums[right] == nums[right - 1]) {
						right--;
					}
					left++;
					right--;
				} else if (ans < 0) {
					left++;
				} else
					right--;
			}
		}
		return result;
	}

}
